package demo.client.socket;

import java.net.SocketException;
import java.nio.ByteBuffer;

import org.jconfig.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import core.client.CoreClient;
import core.util.ErrorList;
import core.util.StringUtil;
import demo.server.run.ServerConfig;

public class DemoClient extends CoreClient<String>{
	
	private String serverAddress;
	private int port;
	private String name;
	private long timeIdle = 0;
	private boolean isSend = true;
	private Logger logI = LoggerFactory.getLogger("LogInfo");
	private Logger logE = LoggerFactory.getLogger("LogError");
	
	public DemoClient(String serverAddress, int port, String name){
		this.serverAddress = serverAddress;
		this.port = port;
		this.name = name;
		loadConfig();
	}

	@Override
	public byte[] encode(Object t) {
		byte[] bt = null;
		if (t instanceof Integer) {
			bt = new byte[4];
			ByteBuffer bb = ByteBuffer.allocate(4).putInt((int)t);
			bb.position(0);
			bb.get(bt);
		} else if (t instanceof String) {
			bt = ((String) t).getBytes();
		} else if (t instanceof byte[]) {
			bt = (byte[]) t;
		}
		return bt;
	}

	@Override
	public String decode() {
		return null;
	}

	@Override
	public void onConnect() {
		startSend();
	}

	@Override
	public void onDisconnect() {
		
	}

	@Override
	public void onIdle() {
		logI.info("{" + name + "}: time idle" );
	}

	@Override
	public void onError(Exception e, String errorType) {
		if (e instanceof SocketException && errorType.equals(ErrorList.E_WRITE)) {
			stopSend();
			disconnect();
			return;
		}
		if (e instanceof SocketException && errorType.equals(ErrorList.E_CONNECTION)) {
			logI.info(getName() + ": Ket noi den server khong thanh cong");
			return;
		}
//		e.printStackTrace();
		logE.error("",e);
	}

	@Override
	public void onSent() {
		
	}
	
	@Override
	public void onReceive(String t) {
		
	}

	@Override
	public void onConfig() {
		setTimeIdle(timeIdle);
		stopReceive();
	}
	
	public void start(){
		connect(serverAddress, port);
	}
	
	public void setNewTimeIdle(long timeIdle){
		this.timeIdle = timeIdle;
	}
	
	public void stopSend(){
		isSend = false;
	}
	
	public String getName(){
		return name;
	}
	
	protected boolean isSend(){
		return isSend;
	}

	private void startSend(){
		ClientSend clientSend = new ClientSend(this);
		clientSend.start();
	}
	
	private void loadConfig(){
		ServerConfig serverConfig = new ServerConfig();
		serverConfig.loadConfig();
		Configuration config = ServerConfig.getConfig();
		String timeIdleString = config.getProperty("TIME_IDLE", "0", "SOCKET");
		if (StringUtil.isCastToInteger(timeIdleString)) {
			timeIdle = new Integer(timeIdleString);
		} else {
			timeIdle = 0;
		}
	}
}
